<template>
  <baidu-map 
    class="bm-view"
    center="北京" 
    :zoom="15"
    scroll-wheel-zoom="true" 
    dragging="true"
    @ready="onMapReady"
  >
    <bm-local-search :keyword=" keyword" :auto-viewport="true" :location="location"></bm-local-search>
  </baidu-map>
  <label>关键词：<input v-model="keyword"></label>
  <label>地区：<input v-model="location"></label>
  <div class="box">
    <el-button @click = "goCancle">取消</el-button>
    <el-button type="primary" @click = "goSure">确定</el-button>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import { useRoute,useRouter } from 'vue-router';
import { ElMessage } from 'element-plus'
const location = ref('北京');
const keyword = ref('百度');
let route = useRoute()
let router = useRouter()
let myFlag = route.query.mapFlag
const map = ref(null);
const geoc = ref(null);
let longitude = ref("")//经度：
let latitude = ref("")//，纬度：
const onMapReady = ({ BMap, map: mapInstance }) => {  
  map.value = mapInstance;
  geoc.value = new BMap.Geocoder();
  map.value.addEventListener("click", function(e) {
    const pt = e.point;
    longitude.value = e.point.lng;
    latitude.value = e.point.lat;

    geoc.value.getLocation(pt, function(rs) {
      // console.log(`经度：${longitude.value}，纬度：${latitude.value}`);
    });
  });
};
let goCancle = () => {
    if(myFlag == 0){
        router.push({
            path:'/HomePage/DeviceMange'
        })
    }
}
let goSure = () => {
    if(myFlag == 0){
        if(longitude.value == "" || latitude.value == ""){
            ElMessage.info('请选择要拾取的坐标')
        }else{
            ElMessage.success('坐标拾取成功')
            // 返回时，将模态框状态存入 sessionStorage
            sessionStorage.setItem('dialogOpen', 'true');
            if(sessionStorage.getItem('flag') == '添加'){
              sessionStorage.setItem('flag','添加')
            }else{
              sessionStorage.setItem('flag','编辑')
            }
            setTimeout(() => {
                router.push({
                    path:'/HomePage/DeviceMange',
                    query:{
                        longitude:longitude.value,
                        latitude:latitude.value,
                    }
                })
            },1000)
        }
    }
}
</script>

<style lang="less" scoped>
.bm-view {
  width: 100%;
  height: 90%;
}
.box{
    width: 150px;
    height:40px;
    position: fixed;
    top: 10px;
    right: 10px;
}
</style>